The slice()
method in JavaScript is used to create a shallow copy of a portion of an array without modifying the original array. It returns a new array containing the selected elements.
start
(optional): The index where extraction begins (inclusive). If omitted, it defaults to 0
.end
(optional): The index where extraction stops (exclusive). If omitted, it defaults to the length of the array.
slice()
does not modify the original array.Comparison: slice()
vs splice()
in JavaScript
Feature | slice() | splice() |
---|---|---|
Purpose | Extracts a portion of an array | Modifies an array by adding/removing elements |
Modifies original array? | ❌ No (returns a new array) | ✅ Yes (changes the original array) |
Returns | A new array with selected elements | The removed elements as an array |
Can add elements? | ❌ No | ✅ Yes |
Parameters | (start, end) | (start, deleteCount, item1, item2, ...) |
slice()
(Non-destructive)
splice()
(Destructive)
splice()
to add elements
slice()
when you only need to extract elements without modifying the original array.splice()
when you need to remove, replace, or insert elements in the original array.